package com.example.security.realm;

import com.example.security.bean.LoginType;
import com.example.security.bean.LoginUser;
import com.example.security.config.CustomizedToken;
import com.example.util.DateUtils;
import com.example.util.str.StringUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 * 系统用户认证
 */
public class ComAuthenticationProvider implements AuthenticationProvider {

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        CustomizedToken customizedToken=(CustomizedToken)authentication;
        if(customizedToken.getUserType().equals(LoginType.USER)){
            return null;
        }
        LoginUser loginUser=new LoginUser((String)customizedToken.getPrincipal(),(String)customizedToken.getCredentials(),customizedToken.getAuthorities());
        loginUser.setUserInfo(customizedToken.getUserInfo());
        loginUser.setToken(StringUtils.getUUID());
        loginUser.setLoginTime(DateUtils.getNowDate().getTime());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        return authenticationToken;
    }

    public boolean supports(Class<?> authentication) {
        return authentication.equals(CustomizedToken.class);
    }
}
